//
//  LCYChatMainViewController.m
//  IMByLinkUs
//
//  Created by lcy on 16/1/14.
//  Copyright © 2016年 lcy. All rights reserved.
//

#import "LCYChatMainViewController.h"
#import "LCYChatMainView.h"
#import "LCYEmoticonPickerView.h"
#import "LCYAttachmentAddView.h"
#import "LCYIMMessage.h"
#import "NSDate+LCYCurrentDate.h"
#import "LCYChatMainCollectionViewCell.h"
#import "LCYIMMessage.h"
#import "LCYEmoticonInfoModel.h"
#import "LCYRecorderManager.h"
#import "LCYAudioVolumeDisplay.h"

@interface LCYChatMainViewController () <LCYChatMainViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, LUPostingMessageCollectionViewCellDelegate, UITextViewDelegate>


@property (nonatomic, strong) LCYAudioVolumeDisplay *volumeDisplayView; // 录音提示视图
@property (nonatomic, strong) LCYRecorderManager *recorderManager; // 处理录音相关事宜

@property (nonatomic, strong) NSMutableArray *emojisInfoArray; // 表情
@property (nonatomic, strong) NSMutableArray *dataArray; // 数据源数组
@property (nonatomic, strong) NSMutableArray *itemHeightArray; // item高度
@property (nonatomic, strong) UIView *darkView; // 阴影View

@property (nonatomic, strong) NSTimer *updateRecordTimer; // 检测录音时长
@property (nonatomic, strong) NSTimer *volumeTimer; // 检测音量
@property (nonatomic, strong) NSDate *date; // 当前日期


@end

@implementation LCYChatMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // 数据持久化
    
    [self.LCYChatView.LCYMainChatView registerClass:[LCYChatMainCollectionViewCell class] forCellWithReuseIdentifier:@"collectionViewPostCell"];
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shouldDeleteEmoticon:) name:@"shouldDelegateEmoticon" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shouldGetEmoticon:) name:@"shouldGetEmoticon" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shouldSendMessage) name:@"shouldSendMessage" object:nil];
}

// View 适配当前屏幕
- (void)loadView
{
    [super loadView];
    self.view.frame = [UIScreen mainScreen].bounds;
}

#pragma mark - 懒加载

- (NSMutableArray *)dataArray
{
    if(_dataArray == nil)
    {
        self.dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)emojisInfoArray
{
    if(_emojisInfoArray == nil)
    {
        self.emojisInfoArray = [NSMutableArray array];
    }
    return _emojisInfoArray;
}

- (NSMutableArray *)itemHeightArray
{
    if(_itemHeightArray == nil)
    {
        self.itemHeightArray = [NSMutableArray arrayWithCapacity:self.dataArray.count];
    }
    return _itemHeightArray;
}

- (LCYAudioVolumeDisplay *)volumeDisplayView
{
    if(_volumeDisplayView == nil)
    {
        // 录音信息展示
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"LCYAudioVolumeDisplay" owner:self options:nil];
        
        // 得到第一个UIView
        self.volumeDisplayView = [nib objectAtIndex:0];
        self.volumeDisplayView.frame = CGRectMake((kLCYScreenWidth - 150) * 0.5, (kLCYScreenHeight - 150) * 0.5, 150, 150);
        self.volumeDisplayView.backgroundColor = [UIColor colorWithRed:0.2008 green:0.1871 blue:0.9986 alpha:0.555878767730496];
        self.volumeDisplayView.layer.shadowColor = [UIColor blackColor].CGColor;
        self.volumeDisplayView.layer.shadowOpacity = 0.5;
        
        self.darkView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kLCYScreenWidth, kLCYScreenHeight - 44)];
        self.darkView.backgroundColor = [UIColor lightGrayColor];
        self.darkView.alpha = 0.8;
        [self.view addSubview:self.darkView];
        
        [self.view addSubview:self.volumeDisplayView];
        
        self.darkView.hidden = YES;
        self.volumeDisplayView.hidden = YES;
    }
    return _volumeDisplayView;
}

- (LCYRecorderManager *)recorderManager
{
    if(_recorderManager == nil)
    {
        self.recorderManager = [[LCYRecorderManager alloc] init];
    }
    return _recorderManager;
}

#pragma mark - 代理方法

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LCYChatMainCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionViewPostCell" forIndexPath:indexPath];
    
    cell.indexPath = indexPath;
    cell.delegate = self;
//    cell.bubbleView.myTextView = nil;
    
    
    // cell控件重用
//    for(id view in cell.contentView.subviews)
//    {
//        [view removeFromSuperview];
//        if(view == cell.bubbleView)
//        {
//            for(UIView *subView in cell.bubbleView.subviews)
//            {
//                if(subView.frame.size.width == 32)
//                {
//                    [subView removeFromSuperview];
//                }
//            }
//        }
//    }
    
    LCYIMMessage *message = self.dataArray[indexPath.row];
    
    
    cell.cellType = message.cellType;
    cell.myMessage = message;
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 返回cell重用后的size
    if(indexPath.row < self.itemHeightArray.count)
    {
        NSNumber *number = self.itemHeightArray[indexPath.row];
        if(number)
        {
            return CGSizeMake(kLCYScreenWidth, [self.itemHeightArray[indexPath.row] floatValue] + 54);
        }
    }
    return CGSizeMake(kLCYScreenWidth, 64);
}


// 点击send发送消息
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // 发送文本
    if ([text isEqualToString:@"\n"]) {
        
        [textView resignFirstResponder];
        
        if(self.LCYChatView.LCYInputTextView.text.length == 0)
        {
            return YES;
        }
        
        // 当前日期
        NSDate *date = [NSDate getCurrentDate];
        
        LCYIMMessage *message = [[LCYIMMessage alloc] initWithSenderId:@"0" senderDisplayName:@"勒宸胤" date:date text:self.LCYChatView.LCYInputTextView.text];
        message.cellType = PostCell;
        
        [self.dataArray addObject:message];
        
        // 清空输入框
        self.LCYChatView.LCYInputTextView.text = @"";
        
        // 刷新
        [self.LCYChatView.LCYMainChatView reloadData];
        
        // 视图滑到底部
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.dataArray.count - 1 inSection:0];
        [self.LCYChatView.LCYMainChatView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:YES];
        
        return NO;
    }
    
    return YES;
}


// 开始录音
- (void)shouldStartRecord
{
    [self showVolumeDisplay];
    
    // 当前日期
    self.date = [NSDate getCurrentDate];
    
    LCYIMMessage *message = [[LCYIMMessage alloc] initWithSenderId:@"0" senderDisplayName:@"勒宸胤" date:_date text:@"正在录音..."];
    message.cellType = PostAudioCell;
    
    [self.recorderManager startRecording];
    
    //检测音量
    _volumeTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(updateVolumes) userInfo:nil repeats:YES];
    
    
    [self.dataArray addObject:message];
    
    // 刷新
    [self.LCYChatView.LCYMainChatView reloadData];
    
    // 视图滑到底部
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.dataArray.count - 1 inSection:0];
    [self.LCYChatView.LCYMainChatView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:YES];
    
}

// 完成录音
- (void)shouldCompleteRecord
{
    [self.recorderManager stopRecording];
    [_updateRecordTimer invalidate];
    [_volumeTimer invalidate];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.dataArray.count - 1 inSection:0];
    
    NSLog(@"%lf", [self.recorderManager recordedTimeInterval]);
    LCYIMMessage *audioMessage = [[LCYIMMessage alloc] initWithSenderId:@"0" senderDisplayName:@"勒宸胤" date:_date text:[NSString stringWithFormat:@"%.0f'", [self.recorderManager recordedTimeInterval]] audioFileName:[self.recorderManager defaultFileName]];
    
    audioMessage.cellType = PostAudioCell;
    
    // 隐藏录音信息
    self.darkView.hidden = YES;
    self.volumeDisplayView.hidden = YES;
    
    [self.dataArray replaceObjectAtIndex:indexPath.row withObject:audioMessage];
    
    // 刷新
    [self.LCYChatView.LCYMainChatView reloadData];
    
    // 视图滑到底部
    [self.LCYChatView.LCYMainChatView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:YES];
}

// 需要刷新item
- (void)needToReloadItemAtIndexPath:(NSIndexPath *)indexPath withItemHeight:(CGFloat)height
{
    // 刷新指定行
    [self.itemHeightArray setObject:[NSNumber numberWithFloat:height] atIndexedSubscript:indexPath.row];
    [self.LCYChatView.LCYMainChatView reloadItemsAtIndexPaths:@[indexPath]];
}

// 播放音频
- (void)tapToPlayAudioWithFileName:(NSIndexPath *)indexPath
{
    LCYIMMessage *message = self.dataArray[indexPath.row];
    [self.recorderManager initAudioPlayerWithUrl:message.audioFileName];
    [self.recorderManager play];
}

// 播放视频
- (void)tapToPlayVideoWithFileURL:(NSIndexPath *)indexPath
{
    
}

#pragma mark - 通知方法
// 删除表情
- (void)shouldDeleteEmoticon:(NSNotification *)note
{
    NSMutableString *str = [NSMutableString stringWithString:self.LCYChatView.LCYInputTextView.text];
    
    if(str.length > 0)
    {
        NSRange range = {str.length - 1, 1};
        
        [str replaceCharactersInRange:range withString:@""];
        
        self.LCYChatView.LCYInputTextView.text = str;
        [self.LCYChatView.LCYInputTextView scrollRangeToVisible:NSMakeRange(str.length, 1)];
    }
}

// 获取表情
- (void)shouldGetEmoticon:(NSNotification *)note
{
    NSDictionary *dic = note.userInfo;
    LCYEmoticonInfoModel *info = dic[@"info"];
    
    NSMutableString *str = [NSMutableString stringWithString:self.LCYChatView.LCYInputTextView.text];
    if (str.length == 0)
    {
        str = [NSMutableString stringWithString:info.name];
        [self.emojisInfoArray addObject:info];
    }else
    {
        str = [NSMutableString stringWithString:[str stringByAppendingString:info.name]];
        [self.emojisInfoArray addObject:info];
    }
    
    self.LCYChatView.LCYInputTextView.text = str;
    [self.LCYChatView.LCYInputTextView scrollRangeToVisible:NSMakeRange(str.length, 1)];
}

// 发送消息
- (void)shouldSendMessage
{
    [self.LCYChatView.LCYInputTextView resignFirstResponder];
    
    if(self.LCYChatView.LCYInputTextView.text.length == 0)
    {
        return;
    }
    
    // 当前日期
    NSDate *date = [NSDate getCurrentDate];
    
    LCYIMMessage *message = [[LCYIMMessage alloc] initWithSenderId:@"0" senderDisplayName:@"勒宸胤" date:date text:self.LCYChatView.LCYInputTextView.text];
    
    [self.dataArray addObject:message];
    
    // 清空输入框
    self.LCYChatView.LCYInputTextView.text = @"";
    
    // 刷新
    [self.LCYChatView.LCYMainChatView reloadData];
    
    // 视图滑到底部
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.dataArray.count - 1 inSection:0];
    [self.LCYChatView.LCYMainChatView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:YES];
    
    // 数据持久化
}

#pragma mark - 私有方法

// 展示录音view
- (void)showVolumeDisplay
{
    [self.view bringSubviewToFront:self.darkView];
    [self.view bringSubviewToFront:self.volumeDisplayView];
    self.darkView.hidden = NO;
    self.volumeDisplayView.hidden = NO;
    
    _updateRecordTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateRecordTime) userInfo:nil repeats:YES];
}

/**
 *  更新音量界面
 */
- (void)updateVolumes
{
    [self.recorderManager.recorder updateMeters];
    float power = [self.recorderManager.recorder averagePowerForChannel:1.0];
    int volume = roundf(power / -10);
    
    volume = volume <= 0 ? 0:volume;
    volume = volume >= 5 ? 5:volume;
    volume = 5 - volume;
    
    [self.volumeDisplayView setAudioVolumeLevel:volume];
}

// 刷新录音时间
- (void)updateRecordTime
{
    int dur = floor(self.recorderManager.recordDurationTime);
    self.volumeDisplayView.recordInfoLabel.text = [NSString stringWithFormat:@"正在录音：%02d:%02d", dur / 60, dur % 60];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
